import React, { Component } from 'react';
import { Button, Spin, Modal, message } from 'antd';
import { WeaDialog, WeaLocaleProvider, WeaMoreButton, WeaFormItem, WeaSelect, WeaTab, WeaTextarea, WeaRichText, WeaInput, WeaError, WeaTools } from 'ecCom';
import * as Api from '../../apis/votingList';

const getLabel = WeaLocaleProvider.getLabel;
const tabDatas = () => ({
    message: { title: getLabel('383607', '消息中心提醒'), key: 'message' },
    email: { title: getLabel('18845', '邮件提醒'), key: 'email' },
    sms: { title: getLabel('17586', '短信提醒'), key: 'sms' },
});
const options = () => [
    {
        key: 'message',
        selected: true,
        showname: getLabel('383607', '消息中心提醒'),
    }, {
        key: 'email',
        selected: false,
        showname: getLabel('18845', '邮件提醒'),
    }, {
        key: 'sms',
        selected: false,
        showname: getLabel('17586', '短信提醒'),
    },
];
const defaultStateContent = {
  emailContent: '',
  emailRichContent: '',
  messageContent: '',
  smsContent: '',
};
export default class VoteUrgent extends Component {
    constructor(props) {
        super(props);
        this.prefixCls = 'vote-dialog-urgent';
        this.options = options();
        this.state = {
            spinning: false,
            selectValue: 'message',
            selectedKey: 'message',
            content: defaultStateContent,
        };
    }

    getInstance = (ref) => {
      if (!this.emailContentRef) {
        this.emailContentRef = ref;
      }
    }

    handleStatusChange = (status) => {
      if (status === 'ready') {
        this.rtInstanceReady = true;
        this.emailContentRef.focus('first');
      }
    }

    renderRemind = () => {
        const { selectValue, selectedKey } = this.state;
        return (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@qvmfil`}
              label={getLabel('501471', '提醒方式')}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 18 }}
              className={`${this.prefixCls}-remind`}
            >
                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@b7uztw`}
                  detailtype={2}
                  options={this.options}
                  value={selectValue}
                  viewAttr={3}
                  onChange={(v) => {
                        if (v && v.indexOf(',') === -1 && v !== 'message') { // just has one selectKey and this key is not message
                            this.setState({ selectedKey: v });
                        } else if (v && !v.includes(selectedKey)) {
                            this.setState({ selectedKey: v.split(',')[0] });
                        } else if (!v) {
                            this.setState({ selectedKey: 'message' });
                        }
                        this.setState({ selectValue: v });
                    }}
                />
            </WeaFormItem>
        );
    }

    renderTab = () => {
        let topTab = [];
        if (this.state.selectValue) {
            for (let value of this.state.selectValue.split(',')) {
                topTab = [...topTab, tabDatas()[value]];
            }
        }
        return topTab;
    }

    renderContent = (selectedKey) => {
        const { content } = this.state;
        const contentKey = content[`${selectedKey}Content`];
        return (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@6nqzmg`}
              label={getLabel('27415', '提醒内容')}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 18 }}
              className={`${this.prefixCls}-content-form`}
            >
                <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@avk8lc`} tipPosition="bottom" ref={selectedKey} error={getLabel('516780', '提醒内容未填写')}>
                    <WeaTextarea ecId={`${this && this.props && this.props.ecId || ''}_WeaTextarea@uwnbj8`}
                      viewAttr={3}
                      value={[contentKey]}
                      onChange={(v) => {
                            let newValue = {
                                ...content,
                                [`${selectedKey}Content`]: v,
                            };
                            this.setState({ content: newValue });
                        }}
                    />
                </WeaError>
            </WeaFormItem>
        );
    }

    renderEmailContent = () => {
        const { content, selectedKey } = this.state;
        const contentKey = content[`${selectedKey}Content`];
        return (
            <div className={`${this.prefixCls}-content`}>
                <p>{getLabel('516750', '邮件主题:')}</p>
                <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@809fao`} tipPosition="bottom" ref={selectedKey} error={getLabel('516756', '邮件主题未填写')}>
                    <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@fdci5k`}
                      viewAttr={3}
                      value={[contentKey]}
                      onChange={(v) => {
                            let newValue = {
                                ...content,
                                [`${selectedKey}Content`]: v,
                            };
                            this.setState({ content: newValue });
                        }}
                    />
                </WeaError>
                <p>{getLabel('391188', '邮件内容：')}</p>
                <div>
                    <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@o5an2l`}
                      viewAttr={3}
                      ref={this.getInstance}
                      value={content[`${selectedKey}RichContent`]}
                      onChange={(v) => {
                            let newValue = {
                                ...content,
                                [`${selectedKey}RichContent`]: v,
                            };
                            this.setState({ content: newValue });
                        }}
                      ckConfig={{
                            toolbar: [
                                { name: 'document', items: ['Source'] },
                                {
                                name: 'paragraph',
                                items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList'],
                                },
                                { name: 'styles', items: ['Format', 'Font', 'FontSize'] },
                                { name: 'colors', items: ['TextColor'] },
                                {
                                name: 'basicstyles',
                                items: ['Bold', 'Italic', 'Underline', 'Strike'],
                                },
                                { name: 'insert', items: ['Image', 'Table', 'Smiley'] },
                            ],
                            height: 260,
                            uploadUrl: '/api/blog/fileupload/uploadimage',
                        }}
                      onStatusChange={this.handleStatusChange}
                    />
                </div>
            </div>
        );
    }

    render() {
        const { visible } = this.props;
        const { spinning, selectedKey, selectValue } = this.state;
        const buttons = [
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7caxbv@onSubmitBtn`} type="primary" onClick={this.onSubmit}>{getLabel('725', '提交')}</Button>,
            <WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@3mlr7o@_WeaMoreButton`} />,
        ];
        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@67hgh4`}
              title={getLabel('516643', '调查催办')}
              iconBgcolor="#6D3CF7"
              icon="icon-coms-investigate"
              visible={visible}
              buttons={buttons}
              onCancel={this.onCancel}
              style={{ width: 700, height: 500 }}
              className={this.prefixCls}
              hasScroll
            >
                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@3mb6po`} spinning={spinning}>
                    { this.renderRemind() }
                    {
                      selectValue && (
                        <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@4lzkn9`}
                          datas={this.renderTab()}
                          keyParam="key" // 主键
                          selectedKey={selectedKey}
                          onChange={v => this.setState({ selectedKey: v })}
                        />
                      )
                    }
                    { selectValue && selectedKey !== 'email' && this.renderContent(selectedKey) }
                    { selectValue && selectedKey === 'email' && this.renderEmailContent() }
                </Spin>
            </WeaDialog>
        );
    }

    // 提交
    onSubmit = () => {
        const { onSubmit, openUnInvitedList, voteid } = this.props;
        const { selectValue, selectedKey, content } = this.state;
        if (!selectValue) {
            Modal.warning({
                title: getLabel('83130', '至少选择一种提醒方式'),
                okText: getLabel('826', '确定'),
            });
            return;
        }

        for (let value of selectValue.split(',')) {
            if (!content[`${value}Content`] && selectedKey === value) { // 当前Tab页
                this.refs[selectedKey].showError();
                return;
            } else if (!content[`${value}Content`] && selectedKey !== value) {
                Modal.warning({
                    title: getLabel('516764', '您有必填提醒内容未填写'),
                    okText: getLabel('826', '确定'),
                });
                return;
            }
        }
        Api.urgentNum({ votingid: voteid }).then((res) => {
            if (res.num * 1) {
                Modal.confirm({
                    title: (
                        <p>
                            {getLabel('516644', '确定给未填写调查的')} <span style={{ color: '#0094FF', cursor: 'pointer' }} onClick={typeof openUnInvitedList === 'function' && openUnInvitedList}>{res.num}</span> {getLabel('516645', '位参与者发送催办提醒？')}
                        </p>
                    ),
                    okText: getLabel('826', '确定'),
                    cancelText: getLabel('31129', '取消'),
                    onOk: this.onOk,
                });
            } else {
                Modal.confirm({
                    title: getLabel('516746', '调查已全部填写，无须进行催办'),
                    okText: getLabel('826', '确定'),
                });
            }
            typeof onSubmit === 'function' && onSubmit(res);
        });
    }

    // 确定
    onOk = () => {
        const { voteid } = this.props;
        const { selectValue, content } = this.state;
        let params = {
            votingid: voteid,
            remindType: selectValue,
            ...content,
        };
        Api.urgent(params).then((res) => {
            if (res.status === '1') {
                message.success(getLabel('385379', '催办成功！'));
                this.onCancel();
            } else {
                message.error(getLabel('384402', '操作失败，请重试！'));
            }
        });
    }

    // 取消 && 退出
    onCancel = () => {
        const { onCancel, voteName, voteid } = this.props;
        this.setState({
            spinning: false,
            selectValue: 'message',
            selectedKey: 'message',
            content: this.defaultContent || defaultStateContent,
        });
        typeof onCancel === 'function' && onCancel();
    }

    // 进入页面请求
    getDatas = () => {
      const { voteid } = this.props;
      this.setState({ spinning: true });
      WeaTools.callApi('/api/voting/view/urgentContent', 'GET', { votingid: voteid }).then((res) => {
        if (res.status === '1') {
          this.defaultContent = {
            emailContent: res.emailContent,
            emailRichContent: res.emailRichContent,
            messageContent: res.messageContent,
            smsContent: res.smsContent,
          };
          this.setState({
            content: this.defaultContent,
          });
        }
        this.setState({ spinning: false });
      });
    }
}
